<template>
  <div 
    class="scroll-container"
    @mouseenter="pauseScroll"
    @mouseleave="resumeScroll"
  >
    <div 
      class="scroll-content"
      :style="{ transform: `translateY(${position}px)` }"
    >
      <div v-for="(item, index) in duplicatedData" :key="index" class="scroll-item">
        · {{ item }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
const originalData = ["测试"];
const data = ref(originalData);
const position = ref(0);
const isPaused = ref(false);
const animationId = ref(null);
const itemHeight = 40; // 每个项目固定高度40px
const scrollSpeed = 0.3; // 滚动速度(px/frame)

// 复制数据实现无缝循环 (复制2份确保足够滚动)
const duplicatedData = computed(() => [...data.value, ...data.value, ...data.value]);

const animate = () => {
  if (isPaused.value) return;
  
  position.value -= scrollSpeed;
  
  // 当滚动完原始数据长度时，重置位置到中间副本的开始处
  if (position.value <= -data.value.length * itemHeight * 1.5) {
    position.value = -data.value.length * itemHeight * 0.5;
  }
  
  animationId.value = requestAnimationFrame(animate);
};

const pauseScroll = () => {
  isPaused.value = true;
  cancelAnimationFrame(animationId.value);
};

const resumeScroll = () => {
  if (!isPaused.value) return;
  isPaused.value = false;
  // 重新计算位置，确保不会跳跃
  if (position.value <= -data.value.length * itemHeight * 1.5) {
    position.value = -data.value.length * itemHeight * 0.5;
  }
  animate();
};

onMounted(() => {
  // 初始位置设为中间副本的开始处
  position.value = -data.value.length * itemHeight * 0.5;
  animate();
});

onUnmounted(() => {
  cancelAnimationFrame(animationId.value);
});
</script>

<style scoped>
.scroll-container {
  height: 40px; /* 容器高度与项目高度相同，每次只显示一个 */
  overflow: hidden;
  position: relative;
}

.scroll-content {
  position: absolute;
  width: 100%;
  will-change: transform; /* 优化性能 */
}

.scroll-item {
  padding-left: 10px;
  height: 40px; /* 固定高度 */
  line-height: 40px; /* 垂直居中 */
  box-sizing: border-box;
}
</style>